package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import net.wanho.entity.News;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author：汤小洋
 * Date：2023-11-07 9:15
 * Description：<描述>
 */
@RestController
@RequestMapping("/news")
@RequiredArgsConstructor
public class NewsController {

    private final ElasticsearchRestTemplate restTemplate;

    /**
     * 创建索引
     */
    @RequestMapping("/create")
    public String create(){
        // 创建索引
        IndexOperations indexOperations = restTemplate.indexOps(News.class);
        indexOperations.create();
        // 创建文档映射
        Document mapping = indexOperations.createMapping(News.class);
        indexOperations.putMapping(mapping);
        return "success";
    }

    /**
     * 批量创建文档
     */
    @RequestMapping("/batch")
    public String batch(){
        List<News> list = new ArrayList<>();
        list.add(new News(1001, "昆明市一年一度的观鸥季已开启", "，民众在滇池边观鸥、喂鸥。随着飞抵“春城”越冬红嘴鸥数量不断增加，云南省昆明市一年一度的观鸥季已开启"));
        list.add(new News(1002, "南京市一年一度的观鸥季已开启", "，民众在滇池边观鸥、喂鸥。随着飞抵“春城”越冬红嘴鸥数量不断增加，云南省昆明市一年一度的观鸥季已开启"));
        list.add(new News(1003, "北京市一年一度的观鸥季已开启", "，民众在滇池边观鸥、喂鸥。随着飞抵“春城”越冬红嘴鸥数量不断增加，云南省昆明市一年一度的观鸥季已开启"));
        list.add(new News(1004, "南昌市一年一度的观鸥季已开启", "，民众在滇池边观鸥、喂鸥。随着飞抵“春城”越冬红嘴鸥数量不断增加，云南省昆明市一年一度的观鸥季已开启"));
        list.add(new News(1005, "北海市一年一度的观鸥季已开启", "，民众在滇池边观鸥、喂鸥。随着飞抵“春城”越冬红嘴鸥数量不断增加，云南省昆明市一年一度的观鸥季已开启"));
        restTemplate.save(list);
        return "success";
    }

    @RequestMapping("/search/{title}")
    public List<News> search(@PathVariable String title){
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchQuery("title", title))
                .build();

        SearchHits<News> hits = restTemplate.search(query, News.class);
        List<News> list = hits.stream()
                .map(hit -> hit.getContent())
                .collect(Collectors.toList());
        return list;
    }



}
